﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common.Net.DesignByContract;

namespace Common.Net.DataStructures
{
    public class ValueMapper<TLeft, TRight>
    {
        readonly List<Tuple<TLeft, TRight>> _mappings = new List<Tuple<TLeft, TRight>>();
        readonly EqualityComparer<TLeft> _leftComparer = EqualityComparer<TLeft>.Default;
        readonly EqualityComparer<TRight> _rightComparer = EqualityComparer<TRight>.Default;

        public ValueMapper()
        {
        }

        public ValueMapper(EqualityComparer<TLeft> leftComparer, EqualityComparer<TRight> rightComparer)
        {
            RequireArg.NotNull(() => leftComparer);
            RequireArg.NotNull(() => rightComparer);

            _leftComparer = leftComparer;
            _rightComparer = rightComparer;
        }

        public IEnumerable<TLeft> LeftValues
        {
            get { return _mappings.Select(m => m.Value1); }
        }
        
        public IEnumerable<TRight> RightValues
        {
            get { return _mappings.Select(m => m.Value2); }
        }

        public void AddMapping(TLeft leftValue, TRight rightValue)
        {
            _mappings.Add(Tuple.New(leftValue, rightValue));
        }

        public TRight GetRightValue(TLeft leftValue)
        {
            return _mappings.Single(m => _leftComparer.Equals(leftValue, m.Value1)).Value2;
        }

        public TLeft GetLeftValue(TRight rightValue)
        {
            return _mappings.Single(m => _rightComparer.Equals(rightValue, m.Value2)).Value1;
        }

    }
}
